//
//  AboutController.swift
//  eBooks
//
//  Created by JunMing on 2019/12/11.
//  Copyright © 2019 赵俊明. All rights reserved.
//

import UIKit
import YYKit
class AboutController: BaseController,EbookOpenEmailProtocol {

    lazy private var authorLabel:YYLabel = {
        let label = YYLabel()
        label.numberOfLines = 0
        return label
    }()
    
    private var dataSource = [AboutModel]()
    private lazy var tableView:UITableView = {
        let tableView = UITableView(frame: self.view.bounds, style: UITableView.Style.grouped)
        tableView.register(UITableViewCell.self, forCellReuseIdentifier: "download")
        tableView.delegate = self
        tableView.dataSource = self
        tableView.backgroundColor = UIColor.white
        tableView.sectionHeaderHeight = 0;
        tableView.sectionFooterHeight = 0;
        // tableView.separatorColor = tableView.backgroundColor
        tableView.tableHeaderView = AboutHeaderView(frame: CGRect.Rect(0, 0, self.view.width, self.view.width*0.45))
        return tableView
    }()

    
    override func viewDidLoad() {
        super.viewDidLoad()
        MobClick.event("set_aboutUs")
        
        getDataSource()
        setupView()
        
        authorLabel.attributedText = "Dev:TonyZhao\nEmail:tonyzhao60@gmail.com".attrStrAddTarget("tonyzhao60@gmail.com", action: { text in
            print(text)
            self.openEmail("联系合作", text, "simplismvip@163.com", "欢迎合作！")
        })
        
        let gesture = UITapGestureRecognizer(target: self, action: #selector(topAction))
        gesture.numberOfTapsRequired = 5
        authorLabel.addGestureRecognizer(gesture)
    }
    
    @objc func topAction(){
        if Tools.getVip() {
            Tools.setVip(false)
        }else {
            Tools.setVip(true)
        }
    }
    
    func setupView() {
        view.addSubview(tableView)
        view.addSubview(authorLabel)
        
        authorLabel.snp.makeConstraints { (make) in
            make.width.equalTo(view.snp.width)
            make.height.equalTo(44)
            if #available(iOS 11.0, *) {
                make.bottom.equalTo(view.safeAreaLayoutGuide.snp.bottom)
            }else {
                make.bottom.equalTo(view.snp.bottom)
            }
        }
        
        tableView.snp.makeConstraints { (make) in
            make.width.equalTo(view.snp.width)
            make.bottom.equalTo(authorLabel.snp.top)
            if #available(iOS 11.0, *) {
                make.top.equalTo(view.safeAreaLayoutGuide.snp.top)
            }else {
                make.top.equalTo(view.snp.top)
            }
        }
    }
    
    func getDataSource() {
        let yszc = "http://www.restcy.com/2018/07/yinsizhengce/"
        let syxy = "http://www.restcy.com/2018/07/14/appanzhuangxukeshiyongxieyi/"
        let sysm = "http://www.restcy.com/source/apps/htmls/master-board.html"
        let pingfen = "https://itunes.apple.com/cn/app/ebook/id1501500754?mt=8"
        for info in [["title":"隐私政策","url":yszc],["title":"使用协议","url":syxy],["title":"使用说明","url":sysm],["title":"评分鼓励","url":pingfen]] {
            dataSource.append(AboutModel(icon: info["url"], title: info["title"]))
        }
    }
}

extension AboutController:UITableViewDelegate,UITableViewDataSource {
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        var cell = tableView.dequeueReusableCell(withIdentifier: "download")
        if cell == nil { cell = UITableViewCell(style: UITableViewCell.CellStyle.default, reuseIdentifier: "download") }
        cell?.accessoryType = .disclosureIndicator
        cell?.selectionStyle = .none;
        cell?.textLabel?.text = dataSource[indexPath.row].title
        cell?.textLabel?.font = UIFont.regular(14.0)
        return cell!
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return dataSource.count
    }
    
    func numberOfSections(in tableView: UITableView) -> Int {
        return 1
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        let urlStr = dataSource[indexPath.row].icon!
        if indexPath.row == 3 {
            if let url = URL(string: urlStr) {
                UIApplication.shared.open(url, options: [:], completionHandler: nil)
            }
        }else{
            let webVC = webViewController()
            navigationController?.pushViewController(webVC, animated: true)
            webVC.loadRequest(urlStr)
        }
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return 44
    }
}


class AboutHeaderView: UIView {
    private let logo = UIImageView(image: UIImage(named: "defaulticon"))
    private let appname = UILabel()
    private let version = UILabel()
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        addSubview(logo)
        addSubview(appname)
        addSubview(version)
        
        logo.layer.cornerRadius = 16
        logo.layer.masksToBounds = true
        
        appname.text = getBundle(key: "CFBundleName")
        appname.textAlignment = .center
        appname.font = UIFont.regular(16.0)
        
        version.text = "version:" + getBundle(key: "CFBundleShortVersionString")
        version.textAlignment = .center
        version.textColor = UIColor.RGB(170, 170, 170)
        version.font = UIFont.regular(11.0)
        
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    override func layoutSubviews() {
        super.layoutSubviews()
        let h:CGFloat = (self.height-70-self.height*0.17)/2
        logo.frame = CGRect.Rect(self.width/2-35, self.height*0.17, 70, 70)
        appname.frame = CGRect.Rect(0, logo.frame.maxY, self.width, h)
        version.frame = CGRect.Rect(0, appname.frame.maxY-10, self.width, h)
    }
    
    
    func getBundle(key: String) -> String {
        return Bundle.main.object(forInfoDictionaryKey: key) as! String
    }
    
}

struct AboutModel {
    var icon:String?
    var title:String?
}

import WebKit
class webViewController: UIViewController {
    
    lazy private var webView:WKWebView = {
        // 创建网页加载的偏好设置
        let prefrences = WKPreferences()
        prefrences.javaScriptEnabled = false
        
        //配置网页视图
        let webConfiguration = WKWebViewConfiguration()
        webConfiguration.preferences = prefrences
        
        let web = WKWebView(frame: .zero, configuration: webConfiguration)
        web.navigationDelegate = self;
        return web
    }()

    override func viewDidLoad() {
        super.viewDidLoad()
        view.addSubview(webView)
        webView.snp.makeConstraints { (make) in
            make.edges.equalTo(view)
        }
    }
    
    func loadRequest(_ urlStr:String)  {
        if let myURL = URL(string: urlStr) {
            let myRequest = URLRequest(url: myURL)
            webView.load(myRequest)
        }
    }
}

// MARK: WKNavigationDelegate
extension webViewController: WKNavigationDelegate {
    //视图开始载入的时候显示网络活动指示器
    func webView(_ webView: WKWebView, didStartProvisionalNavigation navigation: WKNavigation!) {
        UIApplication.shared.isNetworkActivityIndicatorVisible = true
    }
    
    //载入结束后，关闭网络活动指示器
    func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
        UIApplication.shared.isNetworkActivityIndicatorVisible = false
    }
    
    //阻止链接被点击
    func webView(_ webView: WKWebView, decidePolicyFor navigationAction: WKNavigationAction, decisionHandler: @escaping (WKNavigationActionPolicy) -> Void) {
        if navigationAction.navigationType == .linkActivated {
            decisionHandler(.cancel)
            
            let alertController = UIAlertController(title: "Action not allowed", message: "Tapping on links is not allowed. Sorry!", preferredStyle: .alert)
            alertController.addAction(UIAlertAction(title: "OK", style: .default, handler: nil))
            present(alertController, animated: true, completion: nil)
            return
            
        }
        
        decisionHandler(.allow)
    }
}
